<template>
  <div class="alert-container">
    <el-card v-loading="loading">
      <div v-if="alertData">
        <h3>报警详情</h3>
        <el-divider />
        <el-descriptions
          :column="1"
          border
          :label-width="80"
        >
          <el-descriptions-item label="报警ID">{{ alertData.ID }}</el-descriptions-item>
          <el-descriptions-item label="报警内容">
            <el-input
              v-model="alertData.CONTENT"
              type="textarea"
              :disabled="alertData.STATE!='未处理'"
              :autosize="{ minRows: 6, maxRows: 10 }"
            />
          </el-descriptions-item>
          <el-descriptions-item label="当前状态">
            <el-tag :type="stateTagType">{{ alertData.STATE }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ alertData.CREATE_TIME }}</el-descriptions-item>
          <el-descriptions-item label="处理时间">{{ doneTimeDisplay }}</el-descriptions-item>
          <el-descriptions-item label="处理时间">
            <FileUpload
              :src="alertData['PATH'] ? (alertData['PATH'] + `?t=${Date.now()}`) :''"
              @fileSelected="fileSelected"
            >
            </FileUpload>
          </el-descriptions-item>
        </el-descriptions>

        <div class="action-area">
          <el-button
            type="primary"
            :disabled="isProcessed"
            @click="handleProcess"
          >
            {{ processButtonText }}
          </el-button>
        </div>
      </div>
      <el-empty
        v-else
        description="未找到报警信息"
      />
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { dayjs } from 'element-plus';
import myAxios from '@/myAxios/myAxios';
import VueCookie from 'vue-cookie';
import { showSuccess, showWarning } from '@/hooks/useMyMessageBox';
import FileUpload from '@/components/FileUpload.vue';

export default {
  name: 'AlarmView',
  components: {
    FileUpload
  },
  setup () {
    // 响应式状态
    const loading = ref(false);
    const alertData = ref(null);
    const userId = VueCookie.get('userid');

    // 计算属性
    const stateTagType = computed(() => {
      const map = {
        '未处理': 'danger',
        '一级处理': 'success',
        '二级处理': 'success',
        '三级处理': 'success',
        '仓库已处理': 'success',
      };
      return map[alertData.value.STATE] || '';
    });

    const doneTimeDisplay = computed(() =>
      alertData.value.DONE_TIME || '未处理'
    );

    const isProcessed = computed(() => {
      if (userId === '12535') {
        return alertData.value.STATE === '仓库已处理';
      }
      else {
        return ['一级处理', '二级处理', '三级处理'].includes(alertData.value.STATE);
      }
    }
    );

    const processButtonText = computed(() => {
      if (userId === '12535') {
        return isProcessed.value ? '仓库已处理' : '立即处理';
      }
      else {
        return isProcessed.value ? '已完成处理' : '立即处理';
      }
    });

    // 生命周期钩子
    onMounted(() => {
      fetchAlertData();
    });
    const route = useRoute();

    const fileSelected = function (event) {
      if (event) {
        console.log('event.target.files[0]; :>> ', event.target.files[0]);
        alertData.value.img = event.target.files[0];
      }
      else {
        alertData.value.img = undefined;
      }
    };

    const uploadFile = function (file, filename) {
      return new Promise((resolve, reject) => {
        var reader = new FileReader();
        reader.onload = async (e) => {
          // let filename = `${`test`}.jpeg`;D:\WebSite\HTML5MES\QDMES
          let filePath = `D:\\QDMES\\CHER\\driver_tpx_system\\imgs\\`;
          // let filePath = `D:\\WebSite\\HTML5MES\\QDMES\\`;
          let result = await myAxios.uploadFile(e.target.result, filePath, filename);
          if (result.includes('成功')) {
            resolve('上传成功');
          }
          else {
            resolve('上传失败' + result);
          }
        };
        reader.readAsDataURL(file);

      });
    };

    // 方法
    const fetchAlertData = async () => {
      try {
        loading.value = true;
        const alertId = route.query.ID;

        let params = `${alertId}`;
        let res = await myAxios.get(`陈帅廷获取驱动器报警信息`, params);
        console.log('res :>> ', res);
        alertData.value = res[0];

        // 模拟数据
        // alertData.value = {
        //   ID: alertId,
        //   CONTENT: "设备压力异常",
        //   STATE: "未处理",
        //   CREATE_TIME: "2024-03-15 09:45",
        //   DONE_TIME: null,
        //   FIRST_WORKID: "1001",
        //   SECOND_WORKID: "1002"
        // };
      } catch (error) {
        showWarning('数据加载失败');
        // ElMessage.error('数据加载失败');
      } finally {
        loading.value = false;
      }
    };

    const handleProcess = async () => {
      if (!userId) {
        console.log('userid :>> ', userId);
        showWarning('您未登录,请先登录');
        // ElMessage.warning('请先登录');
        return;
      }

      if (!validateUserPermission(userId)) {
        showWarning('您没有操作权限');
        // ElMessage.warning('无操作权限');
        return;
      }

      try {
        loading.value = true;
        let uploadResult = ``;
        let filename = alertData.value.ID + `.jpg`;
        if (!alertData.value.img) {
          uploadResult = '成功';
        }
        else {
          uploadResult = await uploadFile(alertData.value.img, filename);
        }
        if (uploadResult.includes('成功')) {
          const newState = getProcessLevel(userId);
          let doneTime = dayjs().format('YYYY/MM/DD HH:mm:ss');
          let path = alertData.value.img ?
            `http://htqdds.haitian.com:9911/QDMES/CHER/driver_tpx_system/imgs/${alertData.value.ID}.jpg`
            : alertData.value.PATH;
          let params = `${alertData.value.ID}🈹${newState}🈹${doneTime}🈹${alertData.value.CONTENT}🈹${path}`;
          let result = await myAxios.post('陈帅廷更新驱动器报警状态', params);
          if (result.includes('成功')) {
            // 更新本地数据
            alertData.value.STATE = newState;
            alertData.value.DONE_TIME = doneTime;
            if (alertData.value.CONTENT.includes('物料短缺')) {
              if (newState !== '仓库已处理') {
                let pushCode = '12535';
                // let pushCode = '14602';
                let title = '物料短缺报警';
                let description = '产线物料短缺:' + alertData.value.CONTENT;
                let url = window.location.href;
                myAxios.postToWeChat(pushCode, title, description, url);
              }
            }
            else if (alertData.value.CONTENT.includes('设备异常')) {
              if (newState === '一级处理') {
                let title = '设备异常报警';
                let description = '设备异常:' + alertData.value.CONTENT;
                let url = window.location.href;
                myAxios.postToWeChat(alertData.value.SECOND_WORKID, title, description, url);
              }
            }
            showSuccess('处理状态已更新');
          }
          else {
            showWarning('更新失败' + result);
          }
        }


      } catch (error) {
        showWarning('状态更新失败' + error);
      } finally {
        loading.value = false;
      }
    };

    const validateUserPermission = (userId) => {
      let isFirst = alertData.value.FIRST_WORKID.includes(userId);
      let isSecond = alertData.value.SECOND_WORKID.includes(userId);
      return isFirst || isSecond || ['12535', '8951'].includes(userId);
    };

    const getProcessLevel = (userId) => {
      if (userId === '12535') {
        return '仓库已处理';
      }
      else {
        let isFirst = alertData.value.FIRST_WORKID.includes(userId);
        let isSecond = alertData.value.SECOND_WORKID.includes(userId);
        if (isFirst) {
          return '一级处理';
        }
        else if (isSecond) {
          return '二级处理';
        }
        else {
          return '三级处理';
        }
      }
    };

    return {
      loading,
      alertData,
      stateTagType,
      doneTimeDisplay,
      isProcessed,
      processButtonText,
      fileSelected,
      fetchAlertData,
      handleProcess,
      validateUserPermission,
      getProcessLevel,
    };
  }
};
</script>

<style scoped>
.alert-container {
  padding: 1.5rem;
  max-width: 800px;
  margin: 0 auto;
}

h3 {
  margin-bottom: 1rem;
  font-size: 1.4rem;
  color: var(--el-text-color-primary);
}

.action-area {
  margin-top: 2rem;
  text-align: center;
}

:deep(.el-descriptions) {
  margin-top: 1.2rem;
}

.el-empty {
  padding: 2rem 0;
}
</style>